package com.kly.pay.service;

import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.StringUtils;
import com.kly.enums.OrderStatus;
import com.kly.pay.db.dao.POrderDao;
import com.kly.pay.db.dao.PPayTaskDao;
import com.kly.pay.db.entity.POrderEntity;
import com.kly.pay.db.entity.PPayTaskEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@Service
public class RetryTaskServiceImpl implements RetryTaskService {

    @Resource
    PPayTaskDao payTaskDao;
    @Resource
    POrderDao pOrderDao;

    @Override
    public Boolean addTask(String payOrderNo) {

        if (StringUtils.isEmpty(payOrderNo)) {
            return Boolean.FALSE;
        }
        final POrderEntity order = pOrderDao.queryByPayOrderNo(payOrderNo);
        if (order == null) {
            return Boolean.FALSE;
        }
        if (OrderStatus.PAID.getStatus() == order.getStatus() || OrderStatus.CLOSE.getStatus() == order.getStatus()) {
            return Boolean.FALSE;
        }

        PPayTaskEntity task = new PPayTaskEntity();
        task.setStatus(0);
        task.setNextJobTime(getDateMinutesLater(5));
        task.setPayOrderNo(payOrderNo);
        task.setPayType(order.getPayType());
        payTaskDao.insert(task);

        return Boolean.TRUE;
    }


    public static Date getDateMinutesLater(int minutes) {
        Calendar now = Calendar.getInstance();
        now.add(Calendar.MINUTE, minutes);
        String nowDate = DateUtil.getDate(now.getTime(), "yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(nowDate);
        } catch (ParseException pe) {
        }
        return date;
    }
}
